import os
import time

import pandas as pd
import re
import glob
import numpy as np

import telnetlib
import threading


def do_telnet(host_ip, path, username, password):

    # path = r'D:\Users\10079494.A24808550\Desktop\信通院python培训\\'
    # host_ip = r'129.60.161.169'
    # username = 'zte'
    # password = 'zte'

    tn = telnetlib.Telnet()
    try:

        tn.open(host_ip, port=23, timeout=5)
        print('%s connected ssuccess !' % host_ip)

        tn.read_until(b'Username:', timeout=5)
        tn.write(username.encode('ascii') + b'\n')

        tn.read_until(b'Password:', timeout=5)
        tn.write(password.encode('ascii') + b'\n')
        time.sleep(1)

        command_result = tn.read_until(b'#', timeout=5)
        if b'#' not in command_result:
            print('%s登录失败' % host_ip)
        else:
            print('%s登录成功' % host_ip)

    except:

        print('%s网络连接失败' % host_ip)

    command = "show clock"
    command = bytes(command, encoding='utf-8')
    tn.write(command + b'\r\n')
    run_time = tn.read_until(b'#')
    run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]

    command = "show ip ospf neighbor detail"
    command = bytes(command, encoding='utf-8')
    tn.write(command + b'\n')
    time.sleep(1)

    result_list = []
    while (True):
        command_result = tn.read_very_eager().decode('ascii')
        # print(command_result)
        result_list.append(command_result)
        if re.findall(r"--More--", command_result.strip()):
            tn.write(b" ")

        elif re.findall(r"#", command_result.strip()):
            break
        else:
            time.sleep(0.05)
            continue

    result_str = "\n".join(result_list)

    dict_ouput = {}

    dict_ouput["host_ip"] = host_ip
    dict_ouput["time"] = run_time

    startpattern = re.compile(r'OSPF Router with ID (.+)')
    strtext = re.search(startpattern, str(result_str)).group(1)
    dict_ouput["OSPF Router with ID"] = strtext

    startpattern = re.compile(r'Neighbor\s+(\d+.\d+.\d+.\d+)')
    strtext = re.search(startpattern, str(result_str)).group(1)
    dict_ouput["Neighbor"] = strtext

    startpattern = re.compile(r'In the area\s+(.+)')
    strtext = re.search(startpattern, str(result_str)).group(1)
    dict_ouput["area"] = strtext

    startpattern = re.compile(r'State\s+(\w+), ')
    strtext = re.search(startpattern, str(result_str)).group(1)
    dict_ouput["State"] = strtext

    pd_output = pd.DataFrame.from_dict([dict_ouput])

    pd_output['time'] = pd.to_datetime(pd_output['time'])
    pd_output['time'] = pd_output['time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))

    pd_output.to_csv(path+os.sep+r'ospf'+'-'+str(host_ip)+'.csv', index=None, encoding='gb18030')

    tn.close()


def job_get_info(path):

    list_ip = ['129.60.161.169', '129.60.161.170']
    username = 'zte'
    password = 'zte'

    print("Begin......%s" % time.ctime())
    st = time.time()

    for i in range(len(list_ip)):
        t = threading.Thread(target=do_telnet, args=(list_ip[i], path, username, password,))
        t.start()

    print('time cost：', time.time()-st)


if __name__ == '__main__':
    path = r'D:\Users\10079494.A24808550\Desktop\信通院python培训\\'
    job_get_info(path)

    file_list = glob.glob(os.path.join(os.path.abspath(path), r'ospf*.csv'))
    pd_data_o = pd.DataFrame()
    for file in file_list:
        try:
            pd_sheet = pd.read_csv(file, encoding='gb18030', doublequote=False,
                                   converters={u'code': str}, engine="python")
        except:
            print('读取异常')
        pd_data_o = pd.concat([pd_data_o, pd_sheet], axis=0)
